import urllib2
import xml.dom.minidom
import re
import random
import xml.dom.minidom
import time
import binascii

CLOUDMADE_API_KEY= "61e63096df754995bc9be35873db43e1"
CLOUDMADE_OUTPUT_TYPE="plist"
CLOUDMADE_OTHER_PARAMETERS = ""
GEOCODE_REQUEST_TEMPLATE = (
    "http://geocoding.cloudmade.com/%s/geocoding/v2/find.%s?query=%%s%s" %
    (CLOUDMADE_API_KEY,CLOUDMADE_OUTPUT_TYPE, CLOUDMADE_OTHER_PARAMETERS)
)

re_string = r"\s*".join([
    r"<key>centroid</key>",
    r"<dict>",
    r"<key>lat</key>",
    r"<dict>",
    r"<key>lat</key>",
    r"<string>(-?\d+.-?\d+)</string>",
    r"<key>lon</key>",
    r"<string>(-?\d+.-?\d+)</string>",
    r"</dict>",
    r"</dict>",
])

coordinate_re_pattern =  re.compile(re_string)
"""
<key>centroid</key>\s+
<dict>\s+
<key>lat</key>\s+
<dict>\s+
<key>lat</key>\s+
<string>(-?\d+.-?\d+)</string>\s+
<key>lon</key>\s+
<string>(-?\d+.-?\d+)</string>\s+
</dict>\s+
</dict>"""

# coordinate_re_pattern =  re.compile(r"""(<key>)centroid(</key>)\s*<dict>""")

question_re_pattern=re.compile(u"([^\?]+\?)\s(.*)")

def getCoordinatesIfMissing(trail_locality,node) :
    (lat,lon,method,node_name)=(None,None,None,None)
    try :
        node_name = node["name"]
    except :
        node_name = "<unnamed>"
    try :
        (lat,lon,method) = (node["latitude"],node["longitude"],"explicit")
        # raise "Explicit coordinates supplied but geocode anyway"
    except :
        global_address = "%s, %s"%(node["name"], trail_locality)
        url = GEOCODE_REQUEST_TEMPLATE%global_address.replace(" ","+")
        (
            coord_match,type_match,address_match,
            tries_left,stop_trying
        )=(None,None,None,3,False)
        while(stop_trying != True) :
            url_response = urllib2.urlopen(url)
            response_text = unicode(url_response.read().decode('utf-8'))
            coord_match=coordinate_re_pattern.search(response_text)
            if(coord_match) :
                stop_trying=True
            else :
                print "Failed to match"
            tries_left -= 1
            if(tries_left==0) :
                stop_trying = True
            elif(stop_trying!=True) :
                time.sleep(2.0)
        if(coord_match is None) :
            (lat,lon,method) = (0.0,0.0,"geocode failed")
        else :
            (lat,lon,method) = (
                coord_match.group(1),
                coord_match.group(2),
                "geocode succeeded"
        )
    trace_msg = "( %s, %s ) = %s [%s]"% (lat,lon,node_name,method)
    return (lat,lon,trace_msg)

